﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;


public class EnglishSelectLetterWindow : SingletonBaseWindow<EnglishSelectLetterWindow>
{

    #region ui property

    public Text _PageText { get; set; }
    public Transform _Fengche { get; set; }
    public Transform _Cloud1 { get; set; }
    public Transform _Cloud2 { get; set; }
    public Transform _Cloud3 { get; set; }
    public Transform _Cloud_Start { get; set; }
    public Transform _Cloud_End { get; set; }

    public Transform _Letter_Up { get; set; }
    public Transform _Letter_Down { get; set; }
    public RectTransform _Content { get; set; }
    public Button _Btn_KCJS { get; set; }


    #endregion

    private readonly float windmillSpeed = 100;
    private readonly float cloudMoveTime = 100;
    public const int ADS_INDEX = 3;
    public const int BUY_INDEX = 4; // 需要从哪个字母开始购买   0-A 1-B  2-C 3-D
    public const string ADS_TIPS = "观看广告可以解锁D字母的学习";

    private int m_selectLetterIndex; //选中的字母序号
    private bool isLockInput = false;
    private GameAudioSource m_lockAudio;

    System.Action<int> completeCallback;

    private List<SelectLetterActor> m_letterList;

    protected override void OnOpen(params object[] paramArray)
    {
        base.OnOpen(paramArray);
        
#if SUPER_MY
        _Btn_KCJS.gameObject.SetActive(SDKManager.Instance.IsShowGZH());
#endif

        isLockInput = false;
        _Letter_Up.SetActive(false);
        _Letter_Down.SetActive(false);

        UpdatePage(1, 7);
        CreateLetter();
        //UpdateLetterSaleState();

        //this.AddTimerEx(500, () => {

        MoveCloud(_Cloud1);
        MoveCloud(_Cloud2);
        MoveCloud(_Cloud3);
        //});

        //StudyEnglishProgressInfo info = LocalDataManager.Instance.Load<StudyEnglishProgressInfo>(ELocalDataType.StudyEnglishGame);
        //info.letterGameProgress = 4;
        //info.letterProgress = 26;
        //LocalDataManager.Instance.Save(ELocalDataType.StudyEnglishGame, info);

    }

    protected override void OnRefresh()
    {
        base.OnRefresh();

        isLockInput = false;
        UpdateLetterLockState();
        UpdateLetterSaleState();
        UpdateAllLetterActive(true);
    }

    protected override void OnUpdate()
    {
        base.OnUpdate();

        if (_Fengche != null)
        {
            _Fengche.Rotate(new Vector3(0, 0, Time.deltaTime * windmillSpeed));
        }

    }

    protected override void OnClose()
    {
        base.OnClose();

        if (m_lockAudio != null)
        {
            m_lockAudio.Stop();
            m_lockAudio = null;
        }
        if (m_letterList != null)
        {
            foreach (SelectLetterActor actor in m_letterList)
            {
                if (actor != null)
                    GameObject.Destroy(actor.gameObject);
            }
            m_letterList.Clear();
        }
        EnglishLediAnimationWindow.Instance.StopAnimation();
    }

    protected override void AddListeners()
    {
        base.AddListeners();

        _Btn_KCJS.onClick.AddListener(OnButtonKCJSClick);
        EventBus.Instance.AddEventHandler<string>(EventID.ADS_DONE_CALLBACK, OnAdsCallback);
    }

    protected override void RemoveListensers()
    {
        base.RemoveListensers();

        _Btn_KCJS.onClick.RemoveAllListeners();
        EventBus.Instance.RemoveEventHandler<string>(EventID.ADS_DONE_CALLBACK, OnAdsCallback);
    }

    private void OnAdsCallback(string adsName)
    {
        if (adsName == AdsNameConst.Ads_English.Name)
        {
            StudyEnglishProgressInfo info = LocalDataManager.Instance.Load<StudyEnglishProgressInfo>(ELocalDataType.StudyEnglishGame);
            info.adsCount++;
            LocalDataManager.Instance.Save(ELocalDataType.StudyEnglishGame, info);
            OnRefresh();
        }
    }


    #region uievent

    private void OnButtonKCJSClick()
    {
        if (isLockInput)
            return;
        isLockInput = true;

        EnglishLediAnimationWindow.Instance.StopAnimation();
        WindowManager.Instance.OpenWindow(WinNames.EnglishKCJSPanel, EWindowFadeEnum.Auto);
        //WindowManager.Instance.OpenWindow(WinNames.EnglishKCJSPanel);
        UpdateAllLetterActive(false);
    }


#endregion

    public void UpdateLockState(bool value)
    {
        isLockInput = value;
    }

    // 选中字母的时候调用
    public void OnSDKStart()
    {
        SDKManager.Instance.Event(UmengEvent.EnglishLetterA + m_selectLetterIndex);
        SDKManager.Instance.StartLevel(UmengLevel.EnglishLetterA + m_selectLetterIndex);

        Debug.LogError("---------------------  On Event EnglishLetterA! index:" + m_selectLetterIndex);
        Debug.LogError("---------------------  On StartLevel EnglishLetterA! index:" + m_selectLetterIndex);
    }

    // 退出到字母选择界面的时候调用
    public void OnSDKEnd()
    {
        SDKManager.Instance.FinishLevel(UmengLevel.EnglishLetterA + m_selectLetterIndex);

        Debug.LogError("---------------------  On FinishLevel EnglishLetterA! index:" + m_selectLetterIndex);
    }



    public void AddSelectLetterCallback(System.Action<int> callback)
    {
        completeCallback = callback;
        isLockInput = false;
    }

    public void ResetLetterProgress()
    {
        _Content.anchoredPosition = new Vector2(0, _Content.anchoredPosition.y);
    }

    public void UpdatePage(int page, int pageCount)
    {
        _PageText.text = page + " / " + pageCount;
    }




    private void OnLetterClick(SelectLetterActor actor)
    {
        if (isLockInput)
            return;
        isLockInput = true;
        //SelectLetterActor actor = go.GetComponent<SelectLetterActor>();

        if (actor.isPlayAds)
        {
            if (AdsManager.Instance.AdsReady(AdsNameConst.Ads_English))
            {
                TopNoticeManager.Instance.ShowOkTip(ADS_TIPS, () =>
                {
                    if (AdsManager.Instance.AdsReady(AdsNameConst.Ads_English))
                    {
                        AdsManager.Instance.ShowAds(AdsNameConst.Ads_English);
                    }
                    else
                    {
                        Debug.Log("广告还未准备好. name:" + AdsNameConst.Ads_English.Name);
                        OnRefresh();
                    }
                }, OnRefresh);
            }
            else {
                isLockInput = false;
            }
        }
        else if (actor.isBuy)
        {
            if (actor.isLock)
            {
                if (m_lockAudio == null)
                {
                    m_lockAudio = this.PlayAudioEx(StudyAudioName.t_32010);
                    this.AddTimerEx(m_lockAudio.Length, () => {
                        m_lockAudio = null;
                    });
                }
                isLockInput = false;
                return;
            }
            actor.CrossFade(SelectLetterActor.AnimatorNameEnum.Shake, 0.01f);
            this.AddTimerEx(0.5f, () =>
            {

                if (completeCallback != null)
                {
                    completeCallback(actor.LetterIndex);
                }

                m_selectLetterIndex = actor.LetterIndex;
                OnSDKStart();
            });
        }
        else
        {
            //调用购买
            RemveEvent();
            EventBus.Instance.AddEventHandler(EventID.CANCEL_VERITY, this.OnCancelBuy);
            EventBus.Instance.AddEventHandler(EventID.CANCEL_PAY, this.OnCancelBuy);
            PayManager.Instance.Pay((int)MainItemEnum.StudyEnglish, (id, suc) =>
            {
                //Debug.Log(id + "," + suc);
                //if (id == (int)MainItemEnum.StudyEnglish && suc)
                //{

                //}
                RemveEvent();
                OnRefresh();
            }, true, AdsNameConst.Ads_English);
        }

    }

    private void RemveEvent()
    {
        EventBus.Instance.RemoveEventHandler(EventID.CANCEL_VERITY, this.OnCancelBuy);
        EventBus.Instance.RemoveEventHandler(EventID.CANCEL_PAY, this.OnCancelBuy);
    }

    private void OnCancelBuy()
    {
        RemveEvent();
        isLockInput = false;
    }

    private void MoveCloud(Transform target)
    {
        Vector3 endPoint = _Cloud_End.position;
        endPoint.y = target.position.y;
        float maxDistance = Vector3.Distance(_Cloud_Start.position, _Cloud_End.position);
        float currentDistance = Vector3.Distance(target.position, endPoint);
        target.DOMove(endPoint, (currentDistance / maxDistance) * cloudMoveTime).SetEase(Ease.Linear).OnComplete(() => {
            target.position = new Vector3(_Cloud_Start.position.x, target.position.y, target.position.z);
            MoveCloud(target);
        });

    }

    private void CreateLetter()
    {
        if (m_letterList == null)
            m_letterList = new List<SelectLetterActor>();
        if (m_letterList.Count > 0)
            return;

        for (int i = 0; i < 26; i++)
        {
            GameObject go = null;
            if (i % 2 == 0)
            {
                go = GameObject.Instantiate(_Letter_Up.gameObject);
            }
            else
            {
                go = GameObject.Instantiate(_Letter_Down.gameObject);
            }
            go.name = "Letter:" + i.ToString();
            go.SetActive(true);
            go.transform.SetParent(_Content);
            go.ResetTransformForLocal();
            SelectLetterActor letter = go.AddComponentEx<SelectLetterActor>();
            letter.Initialize(i, FEnglishTool.GetEnglishDataID(i));
            letter.GetComponent<Button>().onClick.AddListener(() => {

                OnLetterClick(letter);
            });
            m_letterList.Add(letter);
        }

        GridLayoutGroup glg = _Content.GetComponent<GridLayoutGroup>();
        RectTransform rt = _Content as RectTransform;
        rt.sizeDelta = new Vector2(glg.cellSize.x * 26, rt.sizeDelta.y);

    }

    private void UpdateAllLetterActive(bool value)
    {
        //if (m_letterList != null)
        //{
        //    foreach (GameObject go in m_letterList)
        //    {
        //        if (go != null)
        //            go.SetActive(value);
        //    }
        //}
    }

    // 刷新字母销售状态
    private void UpdateLetterSaleState()
    {
        bool isBuy = PayManager.Instance.IsBuyItem((int)MainItemEnum.StudyEnglish);
        StudyEnglishProgressInfo info = LocalDataManager.Instance.Load<StudyEnglishProgressInfo>(ELocalDataType.StudyEnglishGame);

        foreach (SelectLetterActor actor in m_letterList)
        {
            actor.UpdateSaleState(isBuy, BUY_INDEX);

#if UNITY_IOS
            if (actor.LetterIndex == ADS_INDEX)
            {
                actor.SetAdsState(isBuy ? false : info.adsCount == 0);
            }
#endif

        }
    }


    private void UpdateLetterLockState()
    {
        StudyEnglishProgressInfo info = LocalDataManager.Instance.Load<StudyEnglishProgressInfo>(ELocalDataType.StudyEnglishGame);
        for (int i = 0; i < m_letterList.Count; i++)
        {
            SelectLetterActor actor = m_letterList[i];
            actor.SetLockState(i > info.letterProgress);
        }
    }


}
